<?php
/**
 * com_Easiv3
 * 
 * @author Lukas Gruber
 * @copyright 2012, Lukas Gruber
 * @license GNU/GPLv3 - http://www.gnu.org/licenses/gpl-3.0.html
 * @contact lukasgruber@gmx.net
 * @website http://www.lukasg255.bplaced.net
 */

defined('_JEXEC') or die();

jimport('joomla.application.component.model');
require_once JPATH_COMPONENT.DS.'helpers'.DS.'extensionshelper.php';

class Easiv3ModelManageExtensions extends JModel {

	var $db;
	var $repoDir;
	var $extensionsHelper;
	var $extensionNames = array();
	var $parser;
	var $instances;
	var $packages;

	/**
	 * Constructor which initializes important objects and scans the repository folder for extensions
	 */
	function __construct() {
		parent::__construct();

		$this->repoDir = 'repository';
		$this->extensionsHelper = new ExtensionsHelper($this->repoDir);
		$this->parser = new XmlParser();
		
		$this->db = JFactory::getDBO();
		$this->db->setQuery("SELECT * FROM #__EASIV3_instances ORDER BY id");
		$result = $this->db->loadObjectList();
		
		$this->instances = array();

		for($i=0; $i<count($result); $i++) {
			$this->instances[$i] = $result[$i];
		}
		
		$this->scanRepository();
	}
	
	/**
	 * Function which scans repository for extension archives.
	 */
	function scanRepository() {
		if(!JFolder::exists(JPATH_COMPONENT.DS.$this->repoDir)) {
			JFolder::create(JPATH_COMPONENT.DS.$this->repoDir);
		}
		
		$this->packages = JFolder::files(JPATH_COMPONENT.DS.$this->repoDir, ".zip");
		
		//unpack	
		foreach($this->packages as $package) {
			$this->extensionNames[] = $this->extensionsHelper->unpack(JPATH_COMPONENT.DS.$this->repoDir.DS.$package);
		}
		
		/*
		 * update database according to the newly scanned extensions
		 */
		$this->updateDatabase();		
	}
	
	/**
	 * Function to update the Easiv3 extension database
	 */
	function updateDatabase() {
		$this->db->setQuery("SELECT packagefile, xmlFile FROM #__Easiv3");
		$dbPackages = $this->db->loadObjectList();

		/*
		 * Compare database packagefiles with packagefiles in the repository folder. If no package in the folder to an existing one in 
		 * the database is found it gets deleted from the database
		 */
		foreach($dbPackages as $dbPackage) {
			$delete = true;
				
			foreach($this->packages as $package) {
				//echo "comparing DB ".str_ireplace("|", DS, $dbPackage->packagefile)." with ".JPATH_COMPONENT.DS.$this->repoDir.DS.$package."<br>";
				if(str_ireplace("|", DS, $dbPackage->packagefile) == JPATH_COMPONENT.DS.$this->repoDir.DS.$package) {
					$delete = false;
				}
			}
				
			if($delete) {
				$this->db->setQuery("DELETE FROM #__Easiv3 WHERE packagefile ='".$dbPackage->packagefile."'");
				$this->db->query();

				if(JFile::exists(JPATH_COMPONENT.DS.$this->repoDir.DS.'manifest'.DS.$dbPackage->xmlFile)) {
					JFile::delete(JPATH_COMPONENT.DS.$this->repoDir.DS.'manifest'.DS.$dbPackage->xmlFile);
				}
			}
		}
	}
	
	/**
	 * Modelfunction to get important extension information from the database
	 * 
	 * @return Array with extension information
	 */
	function getExtensions() {
		$this->db->setQuery("SELECT extension, version FROM #__Easiv3");
		$result = $this->db->loadObjectList();
		
		return $result;
	}
	
	/**
	 * Modelfunction to determin the local installstaus of extensions
	 * 
	 * @return Array with installstaus for each extension
	 */
	function getLocalInstallStatus() {
		/*
		 * Array where install status is saved
		 */
		$installStatus = array();

		for($i = 0; $i < count($this->extensionNames); $i++) {
			$status = $this->extensionsHelper->isInstalled($this->extensionNames[$i]);
			$extensionName = $this->extensionNames[$i];
			$installStatus[$extensionName] = $status;
		}

		return $installStatus;
	}
	
	/**
	 * Model function to get all information about the managed isntances instances as objects from the database
	 */
	function getRemoteInstanceObjects() {
		return $this->instances;
	}
	
	/**
	 * This method sends an XML-RPC request to the managed Joomla! Instances. This request contains an array 
	 * with all extensions found in the repository folder.
	 * 
	 * @return Array for each Joomla! instance with the installation status of the found extensions
	 */
	function getRemoteInstallStatus() {
		$installStatus = array();

		$request_method = 'manageextensions.getinstallstatus';
		$request_param = xmlrpc_encode($this->extensionNames);
		
		foreach($this->instances as $instance) {
			$postdata = http_build_query(
				array(
			        'extensions' => $request_param,
				)
			);

			$opts = array('http' =>	array(
			        'method'  => 'POST',
			        'header'  => 'Content-type: application/x-www-form-urlencoded',
					'content' => $postdata
				)
			);

			$context  = stream_context_create($opts);
			
			$instanceUrl = $instance->http_address;
			$response = file_get_contents($instanceUrl."index.php?option=com_Easiv3ri&task=".$request_method."&format=xmlrpc", false, $context);
			
			$installStatus[$instance->name] = xmlrpc_decode($response);
		}
		
		return $installStatus;

	}
}